<template>
  <div>
    <el-form :inline="true" :model="cForm" class="demo-form-inline">
      <!-- 选中哪个项，最终是选中的分类的id -->
      <el-form-item label="一级分类">
        <el-select
          v-model="cForm.category1Id"
          placeholder="请选择"
          @change="changeCategory1"
        >
          <el-option
            :label="c1.name"
            :value="c1.id"
            v-for="(c1) in category1List"
            :key="c1.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="二级分类">
        <el-select
          v-model="cForm.category2Id"
          placeholder="请选择"
          @change="changeCategory2"
        >
          <el-option
            :label="c2.name"
            :value="c2.id"
            v-for="(c2) in category2List"
            :key="c2.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="三级分类">
        <el-select
          v-model="cForm.category3Id"
          placeholder="请选择"
          @change="changeCategory3"
        >
          <el-option
            :label="c3.name"
            :value="c3.id"
            v-for="(c3) in category3List"
            :key="c3.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "CategorySelector",
  data() {
    return {
      cForm: {
        category1Id: "",
        category2Id: "",
        category3Id: "",
      },
      category1List: [],
      category2List: [],
      category3List: [],
    }
  },
  methods: {
    async getCategory1List() {
      const result = await this.$API.category.getCategory1()
      if (result.code === 200) {
        this.category1List = result.data
      }
    },
    async changeCategory1(category1Id) {
      // 重新选择1级分类，2、3级所有的内容需要清空
      this.cForm.category2Id = ""
      this.cForm.category3Id = ""
      this.cForm.category2List = []
      this.cForm.category3List = []

      this.$emit("changeCategory", { categoryId: category1Id, level: 1 })

      const result = await this.$API.category.getCategory2(category1Id)
      if (result.code === 200) {
        this.category2List = result.data
      }
    },
    // 根据第二个分类获取第三个分类，关联操作
    async changeCategory2(category2Id) {
      // 重新选择2级分类的内容，3级分类的内容需要清空
      this.cForm.category3Id = ""
      this.cForm.category3List = []

      this.$emit("changeCategory", { categoryId: category2Id, level: 2 })

      const result = await this.$API.category.getCategory3(category2Id)
      if (result.code === 200) {
        this.category3List = result.data
      }
    },
    // 选中三级分类的id，需要做的事情
    changeCategory3(category3Id) {
      this.$emit("changeCategory", { categoryId: category3Id, level: 3 })
    },
  },
  mounted() {
    this.getCategory1List()
  },
}
</script>

<style>
</style>
